package me.zhengjie.modules.web.service.mybatisplus.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.UserAccount;
import me.zhengjie.modules.system.domain.UserAccountBill;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.mapstruct.UserAccountPlusMapper;
import me.zhengjie.modules.web.domain.user.AddCommissionDTO;
import me.zhengjie.modules.web.enums.BillApprovalStateEnum;
import me.zhengjie.modules.web.enums.BillTypeEnum;
import me.zhengjie.modules.web.service.mybatisplus.IUserAccountBillPlusService;
import me.zhengjie.modules.web.service.mybatisplus.IUserAccountPlusService;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Service
public class UserAccountPlusServiceImpl extends ServiceImpl<UserAccountPlusMapper, UserAccount> implements IUserAccountPlusService {

    @Autowired
    private IUserAccountBillPlusService billPlusService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCommission(AddCommissionDTO dto) {
        if (StringUtils.isBlank(dto.getOpenId()) || Objects.isNull(dto.getType()) || Objects.isNull(dto.getAmount()) || dto.getAmount().compareTo(BigDecimal.ZERO) == 0){
            throw new WeChatException("缺少参数");
        }
        LambdaQueryWrapper<UserAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserAccount::getOpenId,dto.getOpenId());
        List<UserAccount> list = list(wrapper);
        if (CollectionUtils.isEmpty(list)){
            WxUser wxUser = wxUserService.findByOpenId(dto.getOpenId());
            String mobile = "";
            if (Objects.nonNull(wxUser)){
                mobile = wxUser.getMobile();
            }
            Long userId = null;
            if (StringUtils.isNotBlank(mobile)){
                UserDto byMobile = userService.findByMobile(mobile);
                if (Objects.nonNull(byMobile)){
                    userId = byMobile.getId();
                }
            }

            //需要开户
            UserAccount account = new UserAccount();
            account.setOpenId(dto.getOpenId());
            String acctCode = UUID.fastUUID().toString(true);
            account.setAcctCode(acctCode);
            account.setAcctType(0);
            account.setStatus(ConstantUtils.Valid);
            account.setTotalAmount(dto.getAmount());
            account.setUsableAmount(dto.getAmount());
            account.setFrozenAmount(BigDecimal.ZERO);
            account.setCreateTime(DateUtil.TimestampNow());
            account.setMobile(mobile);
            account.setSysUserId(userId);
            boolean result = save(account);
            if (!result){
                throw new WeChatException("开户失败");
            }
            UserAccountBill bill = new UserAccountBill();
            bill.setAcctNo(acctCode);
            bill.setOpenId(dto.getOpenId());
            bill.setBillStatus(ConstantUtils.Valid);
            bill.setAmount(dto.getAmount());
            bill.setBillType(BillTypeEnum.Income.getBillType());
            bill.setApprovalState(BillApprovalStateEnum.Success.getApprovalState());
            bill.setBizNo(dto.getOrderSn());
            bill.setCreateTime(DateUtil.TimestampNow());
            bill.setBizSource(dto.getType());
            bill.setMobile(mobile);
            bill.setSysUserId(userId);
            billPlusService.save(bill);
            return true;
        }else {
            UserAccount account = list.get(0);
            account.setTotalAmount(account.getTotalAmount().add(dto.getAmount()));
            account.setUsableAmount(account.getUsableAmount().add(dto.getAmount()));
            account.setUpdateTime(DateUtil.TimestampNow());
            boolean result = false;
            try {
                result = saveOrUpdate(account);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!result){
                throw new WeChatException("入账失败");
            }
            UserAccountBill bill = new UserAccountBill();
            bill.setAcctNo(account.getAcctCode());
            bill.setOpenId(dto.getOpenId());
            bill.setBillStatus(ConstantUtils.Valid);
            bill.setAmount(dto.getAmount());
            bill.setBillType(BillTypeEnum.Income.getBillType());
            bill.setApprovalState(BillApprovalStateEnum.Success.getApprovalState());
            bill.setBizNo(dto.getOrderSn());
            bill.setCreateTime(DateUtil.TimestampNow());
            bill.setBizSource(dto.getType());
            bill.setMobile(account.getMobile());
            bill.setSysUserId(account.getSysUserId());
            billPlusService.save(bill);
            return true;
        }
    }
}
